#ifndef SHENLAN_GLITCH
#define SHENLAN_GLITCH

float Glitch_Wave0(float x, float y)
{
    return frac(sin(dot(float2(x, y), float2(12.9898, 78.233))) * 43758.5453) - 0.5;
}

half Glitch_Wave1(float uvOnePath, float4 factor, float t)
{
    half glitch = uvOnePath * factor.z + factor.y * t;
    half2 sig = fmod(floor(0.5 * glitch + half2(0, 0.5)), 2);
    glitch = frac(glitch);
    half x0 = lerp(glitch, 1 - glitch, sig.x);
    x0 = lerp(x0, 1 - x0, sig.y);
    half jitter = x0 * saturate(factor.x);
    return jitter;
}

half Glitch_Wave2(float uvOnePath, float4 factor, float t)
{
    half2 glitch = uvOnePath * factor.z * half2(1, 0.37) + abs(factor.y) * t * half2(1, 0.86);
    half4 sigXY = fmod(floor(0.5 * glitch.xxyy + half4(0, 0.5, 0, 0.5)), 2);
    glitch = frac(glitch);
    half2 x0 = lerp(glitch, 1 - glitch, sigXY.xz);
    x0 = lerp(x0, 1 - x0, sigXY.yw);
    half jitter = (length(x0) - 0.5) * saturate(factor.x) * sign(factor.y) ;
    return jitter;
}

half Glitch_Wave4(float4 glitch, float4 factor)
{
    half4 sigXY = fmod(floor(0.5 * glitch.xxyy + half4(0, 0.5, 0, 0.5)), 2);//两条抛物线形的波浪
    half4 sigZW = fmod(floor(0.5 * glitch.zzww + half4(0, 0.5, 0, 0.5)), 2);//两条抛物线形的波浪
    glitch = frac(glitch);
    half4 x0 = lerp(glitch, 1 - glitch, half4(sigXY.xz, sigZW.xz));
    x0 = lerp(x0, 1 - x0, half4(sigXY.yw, sigZW.yw));
    half jitter = (length(x0) - 1) * saturate(factor.x) * sign(factor.y);
    return jitter;
}

half Glitch_Line(float4 glitch, float4 factor)
{
    
    half jitter = max(length(abs(frac(glitch) - 0.5)) + factor.w - 1.5, 0) * saturate(factor.x) * sign(factor.y);
    return jitter;
}

half Glitch_Cube(float4 random,float2 uv, float4 factor)
{
    half4 glitch = floor(uv.x * factor.y * random) * half4(1, -0.37, 0.13, 0.7) + floor(uv.y * factor.z * random) * half4(0.3, -0.37, 0.2, 0.5);
    half jitter = max(length(frac(glitch)) + factor.w - 1.5, 0) * saturate(factor.x);
    return jitter;
}

float Glitch_Dither(float2 screenUV_)
{
    float2 uv = screenUV_.xy * _ScreenParams.xy;
    float DITHER_THRESHOLDS[16] = {
        1.0 / 17.0, 9.0 / 17.0, 3.0 / 17.0, 11.0 / 17.0,
        13.0 / 17.0, 5.0 / 17.0, 15.0 / 17.0, 7.0 / 17.0,
        4.0 / 17.0, 12.0 / 17.0, 2.0 / 17.0, 10.0 / 17.0,
        16.0 / 17.0, 8.0 / 17.0, 14.0 / 17.0, 6.0 / 17.0
    };
    uint index = (uint(uv.x) % 4) * 4 + uint(uv.y) % 4;
    return DITHER_THRESHOLDS[index];
}

float Glitch_Dither(float2 screenUV_,float2 screenSize)
{
    float2 uv = screenUV_.xy * screenSize.xy;
    float DITHER_THRESHOLDS[16] = {
        1.0 / 17.0, 9.0 / 17.0, 3.0 / 17.0, 11.0 / 17.0,
        13.0 / 17.0, 5.0 / 17.0, 15.0 / 17.0, 7.0 / 17.0,
        4.0 / 17.0, 12.0 / 17.0, 2.0 / 17.0, 10.0 / 17.0,
        16.0 / 17.0, 8.0 / 17.0, 14.0 / 17.0, 6.0 / 17.0
    };
    uint index = (uint(uv.x) % 4) * 4 + uint(uv.y) % 4;
    return DITHER_THRESHOLDS[index];
}


#endif